<!--
 * @Date: 2023-03-11 18:56:50
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-11 20:34:58
 * @FilePath: \A19\frontend\src\components\RunCode\EditExp.vue
-->
<template>
    <Frame v-if="experiment">
        <template #header>
            {{ experiment?.name }}
        </template>
        <template #list>
            <List :questions="experiment.questions" :current-question="currentQuestion" :clicked="selected"></List>
        </template>
        <template #controllers>
            <span class="hint" style="margin-right: 20px;" > 语言环境:</span>
            <el-select  style="margin-right: 20px;" v-model="form2.language" class="m-2" placeholder="Select" size="default">
                <el-option
                v-for="item in lans"
                :key="item"
                :label="item"
                :value="item"
                />
            </el-select>
            <ElButton @click="end" plain type="primary">结束编辑</ElButton>
        </template>
        <template #panel>
            <div v-if="currentQuestion">
                <ElForm :model="currentQuestion" ref="formInstance" :rules="rules" :label-width="100">
                    <el-form-item label="问题描述" prop="description">
                        <el-input v-model="currentQuestion.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="输入样例" prop="input">
                        <el-input v-model="currentQuestion.input" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="输出样例" prop="output">
                        <el-input v-model="currentQuestion.output" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="分值" prop="score">
                        <ElInputNumber v-model="currentQuestion.score" :min="1"></ElInputNumber>
                    </el-form-item>
                    <el-form-item>
                        <ElButton @click="save" type="primary" plain>保存</ElButton>
                        <ElButton @click="reset" plain>重置</ElButton>
                    </el-form-item>
                </ElForm>
            </div>
            <div v-else>
                <div style="height: 200px;line-height: 200px;">选择题目编辑</div>
            </div>
        </template>
    </Frame>

    <ElDialog 
        v-model="dialogVisiable"
        title="创建实验"
        width="30%"
        :show-close="false"
    >
        <ElForm ref="form2Instance" :model="form2" :rules="form2Rule" :label-width="100">
            <ElFormItem label="实验名称" prop="name" >
                <ElInput v-model="form2.name"></ElInput>
            </ElFormItem>
            <ElFormItem label="语言环境" prop="lan">
                <el-select v-model="form2.language" class="m-2" placeholder="Select" size="default">
                    <el-option
                    v-for="item in lans"
                    :key="item"
                    :label="item"
                    :value="item"
                    />
                </el-select>
            </ElFormItem>
            <el-form-item label="开始时间" prop="time">
                <el-date-picker
                    v-model="form2.startTime"
                    type="datetime"
                    placeholder="Select date and time"
                />
            </el-form-item>
            <el-form-item label="结束时间" prop="time">
                <el-date-picker
                    v-model="form2.endTime"
                    type="datetime"
                    placeholder="Select date and time"
                />
            </el-form-item>
        </ElForm>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisiable = false">取消</el-button>
                <el-button type="primary" @click="upload">
                Confirm
                </el-button>
            </span>
        </template>
    </ElDialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { useClientStore } from '../../pinia/stores/client';
import { experiment } from '../../shared/types/experiments';
import {  FormInstance, FormRules } from 'element-plus';

let loadingInstance:any
const route = useRoute()
const router = useRouter()
const expId = route.params.expId as string
const {client} = storeToRefs(useClientStore())

const experiment = ref<experiment>()
const currentQuestion = ref<{
    description: string,
    input: string,
    output: string,
    score: number,
}>()
const editingQuestion = ref<{
    description: string,
    input: string,
    output: string,
    score: number,
    saved:boolean
}>()
const selected = async (question:{
    description: string,
    input: string,
    output: string,
    score: number,
}) =>{
    if(!currentQuestion.value || !editingQuestion.value){
        currentQuestion.value = question
        editingQuestion.value = {
            ...question,
            saved:false
        }
    }
    if(
        currentQuestion.value!.description === editingQuestion.value!.description &&
        currentQuestion.value!.input === editingQuestion.value!.input &&
        currentQuestion.value!.output === editingQuestion.value!.output &&
        currentQuestion.value!.score === editingQuestion.value!.score
    ){
        currentQuestion.value = question
        editingQuestion.value = {
            ...question,
            saved:false
        }
        return
    }
    if(editingQuestion.value?.saved === false){
        try {
            await ElMessageBox.confirm('是否保存？')
            save()
        } catch (error) {
            console.log(error);
            reset()
        }
    }
    currentQuestion.value = question
    editingQuestion.value = {
        ...question,
        saved:false
    }
}
const save = () =>{
    editingQuestion.value!.saved = true
}
const reset = () =>{
    if(!editingQuestion.value) return
    currentQuestion.value!.description = editingQuestion.value.description
    currentQuestion.value!.input = editingQuestion.value.input
    currentQuestion.value!.output = editingQuestion.value.output
    currentQuestion.value!.score = editingQuestion.value.score
}


const form2 = ref({
    name:'',
    language:'不限' as 'cpp' | 'java' | 'rust' | 'javascript' | 'python3' | '不限',
    startTime:new Date(),
    endTime:new Date(),
})
const form2Rule:FormRules = {
    name:{
        required:true,
        message:'请填写实验名称',
        trigger:'blur'
    },
    // lan:{
    //     required:true,
    //     message:'请选择语言环境',
    //     trigger:'blur'
    // }
}
const form2Instance = ref<FormInstance>()
const dialogVisiable = ref(false)
const lans = reactive(['cpp' , 'java' , 'rust' , 'javascript' , 'python3' , '不限'])
const end = () =>{
    dialogVisiable.value = true
}
const upload = async () =>{
    dialogVisiable.value = false
    loadingInstance = ElLoading.service({
        target:'#createTest'
    })
    try {
        await form2Instance.value!.validate()
        const ret = await client.value.callApi('Experiment/EndEdit',{
            _id:experiment.value!._id,
            ...form2.value,
            questions:experiment.value!.questions
        })
        if(ret.isSucc){
            ElMessage.success('编辑成功')
            router.back()
        }

    } catch (error) {
        console.log(error);
    }
    loadingInstance.close()
}


onMounted(async ()=>{
    loadingInstance = ElLoading.service({
        target:'#createTest'
    })

    if(!expId){
        ElMessage.error('不存在')
        return
    }

    const ret = await client.value.callApi('Experiment/GetOneExpById',{
        expId:expId
    })
    if(ret.isSucc){
        experiment.value = ret.res.exp
        form2.value.name = experiment.value.name
        form2.value.startTime = experiment.value.startTime
        form2.value.endTime = experiment.value.endTime
        form2.value.language = experiment.value.language as 'cpp' | 'java' | 'rust' | 'javascript' | 'python3' | '不限'
    }

    loadingInstance.close()
})

const rules: FormRules = {
    description:{
        required:true,
        message:'请输入问题描述',
        trigger:'blur'
    },
    input:{
        // required:true,
        // message:'请输入输入样例',
        // trigger:'blur'
    },
    output:{
        required:true,
        message:'请输入输出样例',
        trigger:'blur'
    },
}
</script>

<style lang="less" scoped>

</style>